<?php
/*
 * @project CreativeFramework
 * @version <#RELEASE_VERSION#>
 * @license GNU Lesser General Public License
 * @author Jimmie Lin
 */

class Main {

	public function config_value($key, $force_reload = false) {
		if(!isset($this->conf_values_array) or $force_reload == true) {
			global $DB;
			$this->conf_values_array = array();
			$q = $DB->Driver->simple_select("configs", "`key`, `value`");
			while($a = $DB->Driver->fetch_array($q)) {
				$this->conf_values_array[$a['key']] = $a['value'];
			}
		}
		
		if(isset($this->conf_values_array[$key])) {
			return $this->conf_values_array[$key];
		}
		else return false;
	}
	
	public function update_config_value($key, $val) {
		// Build an update query,
		global $DB;
		$query = $DB->Driver->update_query(
			"configs",
			array("key", $key),
			array(
				"value" => $val
			)
		);
		return $query;
	}
	
	public function write_acp_log($action, $uid = 0) {
		global $DB;
		if(!$uid) $uid = $_SESSION["cf_uid"];
		// Good, let's go
		$query = $DB->Driver->insert_query("acp_logs",
			array(
				"content" => $action,
				"uid" => intval($uid)
			)
		);
		return $query;
	}
	
	public function nav_array_generate() {
		// Interface
		$this->Interface = APP_TYPE;
		// Get it
		global $DB, $Lang;
		$q = $DB->Driver->simple_select($this->Interface."_nav", "*", "", array(array("order", "order", "ASC")));
		while($a = $DB->Driver->fetch_array($q)) {
			// Get language var title
			if(preg_match("/LANG=/si", $a['title'])) { // Oh, hai.
				// Preg match it out
				preg_replace("/LANG=\"(.*)\"/sie", "\$langvar = '$1';", $a['title']);
				$a['title'] = $Lang->getFormattedKey($langvar);
			}
			$this->nav_array[] = $a;
		}
		return $this->nav_array;
	}
	
	// http://stackoverflow.com/questions/834875/recursive-cast-from-simplexmlobject-to-array
	function _convertXmlObjToArr($obj, &$arr) { 
		$children = $obj->children(); 
		foreach ($children as $elementName => $node) 
		{ 
			$nextIdx = count($arr); 
			$arr[$nextIdx] = array(); 
			$arr[$nextIdx]['name'] = strtolower((string)$elementName); 
			$arr[$nextIdx]['attributes'] = array(); 
			$attributes = $node->attributes(); 
			foreach ($attributes as $attributeName => $attributeValue) 
			{ 
				$attribName = strtolower(trim((string)$attributeName)); 
				$attribVal = trim((string)$attributeValue); 
				$arr[$nextIdx]['attributes'][$attribName] = $attribVal; 
			} 
			$text = (string)$node; 
			$text = trim($text); 
			if (strlen($text) > 0) 
			{ 
				$arr[$nextIdx]['text'] = $text; 
			} 
			$arr[$nextIdx]['children'] = array(); 
			$this->_convertXmlObjToArr($node, $arr[$nextIdx]['children']); 
		} 
		return; 
	}
}
